# coding=utf-8
"""
@author : leecrest
@time   : 2014/8/11 21:57
@brief  : 将目录下的jpg以及同名mask文件合并转化成png文件
"""


import os
import Image

IMAGE_JPG = ".jpg"
IMAGE_PNG = ".png"
IMAGE_MASK = "_alpha_mask"


def ScanPath(sIn, sOut, bDelSrc):
	for sPath in os.listdir(sIn):
		sFull = os.path.join(sIn, sPath)
		if os.path.isdir(sFull):
			ScanPath(sFull, sOut, bDelSrc)
		elif os.path.isfile(sFull):
			sName, sExt = os.path.splitext(sPath)
			if sExt.lower() != IMAGE_JPG:
				continue
			if IMAGE_MASK in sName.lower():
				continue
			sMask = os.path.join(sIn, sName+IMAGE_MASK)
			if not os.path.exists(sMask):
				continue
			sNewPath = os.path.join(sOut, sName+IMAGE_PNG)
			Convert(sFull, sMask, sNewPath, bDelSrc)


def Convert(sOld, sMask, sNew, bDelSrc):
	print "[%s] + [%s] => [%s]" % (sOld, sMask, sNew)
	imgOld = Image.open(sOld)
	imgMask = Image.open(sMask)
	imgNew = HideMaskInImage(imgOld, imgMask)
	imgNew.save(sNew)
	if bDelSrc:
		os.remove(sOld)
		os.remove(sMask)


def HideMaskInImage(img, info):
	if img.mode != "RGBA":
		img = img.convert("RGBA")
	if info.mode != "L" and info.mode != "1":
		info = info.convert("L")
	img.putalpha(info)
	return img


if __name__ == "__main__":
	ScanPath("./", "./", True)

